﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using dnlib.DotNet;
using dnlib.DotNet.Resources;
using dnlib.DotNet.Writer;
using dnlib.IO;

namespace 主程序
{
    class Program
    {
        static void Main(string[] args)
        {
            var rm = Properties.Resources.ResourceManager;
            Console.WriteLine(rm.GetString("ConfigJson"));
            WriteUpdate("ConfigJson","oooooooooooooo");
            Console.ReadLine();
        }



        [DllImport("kernel32.dll")]
        public static extern uint WinExec(string lpCmdLine, uint uCmdShow);


        public static void WriteUpdate(string name,string value)
        {
            string selfName =Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);

            ModuleDefMD module = ModuleDefMD.Load(Properties.Resources.更新程序);

            EmbeddedResource resx =
                (EmbeddedResource)module.Resources.Find(module.Assembly.Name + ".Properties.Resources.resources");

            ResourceElementSet elementSet = dnlib.DotNet.Resources.ResourceReader.Read(module, resx.Data);
            try
            {
                ResourceElement element = elementSet.ResourceElements.First(s => s.Name == "FileName");
                element.ResourceData = new BuiltInResourceData(ResourceTypeCode.String, selfName);
                elementSet.Add(element);

                ResourceElement element1 = elementSet.ResourceElements.First(s => s.Name == "Name");
                element1.ResourceData = new BuiltInResourceData(ResourceTypeCode.String, name);
                elementSet.Add(element1);

                ResourceElement element2 = elementSet.ResourceElements.First(s => s.Name == "Value");
                element2.ResourceData = new BuiltInResourceData(ResourceTypeCode.String, value);
                elementSet.Add(element2);


                MemoryStream ms = new MemoryStream();
                dnlib.DotNet.Resources.ResourceWriter.Write(module, ms, elementSet);
                resx.Data = new MemoryImageStream(0, ms.GetBuffer(), 0, ms.GetBuffer().Length);

                if (module.IsILOnly)
                    module.Write("更新程序.exe", new ModuleWriterOptions(module));
                else
                    module.NativeWrite("更新程序.exe");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }
            module.Dispose();
            ProcessStartInfo psi = new ProcessStartInfo("更新程序.exe");
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.CreateNoWindow = true;
            Process.Start(psi);
            Environment.Exit(0);
        }
    }
}
